//
//  ST_AdvertManger.swift
//  btvideo
//
//  Created by Jason on 2021/11/1.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import Foundation
import RealmSwift
import SDWebImage
import SwiftyUserDefaults


class ST_AdvertManger: NSObject {
    
    static let shared = ST_AdvertManger()
    
    override init() {
        super.init()
    }
    
    /// 广告先改一下
    func fetch_advert_list(){
        
        
        JVrequest(PH.fetchAdvertImageApi, success: { (json) in
            
            print("广告 返回:",json)
            
            let realm = try! Realm()
            
            let data0 = json["data"]["man"]
            
//            删除不存在的 Adv
            let old = Array(realm.objects(ST_AdvertModel.self))
                
            var oldSet =  Set(old.map { (adv) -> Int in
                return adv.id
            })
            
            var currSet = Set<Int>()
            
            for item in data0.arrayValue{
                
                let m  = ST_AdvertModel()
                
                m.id = item["id"].intValue
                
                m.feature_name = item["feature_name"].stringValue
                
                m.nickname = item["nickname"].stringValue
                
                m.content = item["content"].stringValue
//                展示性别取反 1 男 2女 -> 2 男 1女
                m.sex = 2
                
                currSet.update(with: m.id)
                
                try! realm.write {
                    realm.add(m, update: Realm.UpdatePolicy.all)
                }
                
            }
            
            let data1 = json["data"]["woman"]
            
            for item in data1.arrayValue{
                
                let m  = ST_AdvertModel()
                
                m.id = item["id"].intValue
                
                m.feature_name = item["feature_name"].stringValue
                
                m.nickname = item["nickname"].stringValue
                
                m.content = item["content"].stringValue
//                展示性别取反 1 男 2女 -> 2 男 1女
                m.sex = 1
                
                currSet.update(with: m.id)
                
                try! realm.write {
                    realm.add(m, update: Realm.UpdatePolicy.all)
                }
            }
            
            
            oldSet.subtract(currSet)
            
            print("删除的广告 ID Set:",oldSet)
            
            
            let objectsToDelete = realm.objects(ST_AdvertModel.self).filter("id IN %@", oldSet)
            
            try! realm.write {
                realm.delete(objectsToDelete)
            }
            
//            back_thread_execute(afterDelay: 7) {
                self.cacheIndx = 0
                self.cache_advert_image()
//            }
            
        }) { (code, err) in
            
            main_thread_execute(afterDelay: 3) {
                self.fetch_advert_list()
            }
            
        }
    }
    

    /**
     必须要在主线程执行
     */
    func get_advert()->ST_AdvertModel?{
        
        
        guard let currSex = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex else { return nil }
        
        let result = queryAdvert(sex: currSex)
        
        Defaults[.CurrentAdvertIndex] = Defaults[.CurrentAdvertIndex] + 1
        
        return result
    }
    
    fileprivate func queryAdvert(sex:ST_SEX)->ST_AdvertModel?{
        
        let realm = try! Realm()
        
        let list = realm.objects(ST_AdvertModel.self).filter("sex = %d", sex.rawValue).sorted(byKeyPath: "id")
        
        if list.count < 1{
            return nil
        }
        
        let index = Defaults[.CurrentAdvertIndex]
        
        let currIndex = index%list.count
        
        let result = list[safe:currIndex]
        
        return result
    }
    
    var cacheIndx = 0
    
    fileprivate func cache_advert_image(){
        
        let realm = try! Realm()
        
        let list = realm.objects(ST_AdvertModel.self).sorted(byKeyPath: "id")
        
        guard let item = list[safe:cacheIndx] else{
            return
        }
        
        
        
        let url = item.content.advert_image_url_str().url
        
        let key = SDWebImageManager.shared.cacheKey(for: url)
        
        
        if SDImageCache.shared.diskImageDataExists(withKey: key){
            
            print("广告图片 已经有了")
            cacheIndx += 1
            cache_advert_image()
            
            return
        }
        
        SDWebImageDownloader.shared.downloadImage(with: url) { (img, da, er, f) in
         
            SDImageCache.shared.storeImageData(toDisk: da, forKey: key)
            
            back_thread_execute(afterDelay: 7) {
                self.cacheIndx += 1
                self.cache_advert_image()
            }
            
            if img != nil {
                print("广告图片 下载完成 URL:",url ?? "无")
            }
        }
    }
    
}


class ST_AdvertModel: Object {
    
    @objc dynamic var id = 0
    
    @objc dynamic var feature_name = ""
    
    @objc dynamic var nickname = ""
    
    @objc dynamic var content = ""
    /**
        展示性别取反 1 男 2女 -> 2 男 1女
     */
    @objc dynamic var sex = 1
    
    override static func primaryKey() -> String? {
        return "id"
    }
}
